package org.millioncall.yueyoga.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 摄像头拍摄图片
 * 
 * @author zangjinyu
 * @since 1.0.0(2014-7-16)
 * @version 1.0.0
 *
 */
public class AvatarServlet extends HttpServlet {
	private static final long serialVersionUID = -4821903640654190862L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String type = request.getParameter("type");
		String memberId = request.getParameter("photoId");
		HttpSession session = request.getSession();

		// 这个方法是swf提交，如果是拍照的，有三次提交
		String dirPath = getServletConfig().getServletContext()
				.getRealPath("/");
		String fileName = UUID.randomUUID().toString() + ".jpg";
		// request.getParameter("radom");页面传过来的参数

		String realFilePath = dirPath;
		if (!realFilePath.endsWith("/")) {
			realFilePath += "/";
		}
		realFilePath += "upload/" + fileName;

		try {
			File file = new File(realFilePath);
			if (!file.exists()) {
				file.createNewFile();
			}

			FileOutputStream dos = new FileOutputStream(file);
			int x = request.getInputStream().read();
			while (x > -1) {
				dos.write(x);
				x = request.getInputStream().read();
			}
			dos.flush();
			dos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		String statusText = "Successfully Saved";

		if ("big".equals(type)) {
			session.setAttribute("memberAvatar", "upload/" + fileName);
		} else if ("small".equals(type)) {
			statusText = (String) session.getAttribute("memberAvatar");
			session.removeAttribute("memberAvatar");
		}

		// 此处必需返回这种格式,要不然不会第二次调用
		// {"data":{"urls":["1243251304_big.jpg"]},"status":1,"statusText":"保存存成功!"}
		String s = "{\"data\":{\"urls\":[\"" + fileName
				+ "\"]},\"status\":1,\"statusText\":\"" + statusText + "\"}";

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println(s);
		out.flush();
		out.close();
	}

}
